﻿using System;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using CRM.Models;
using CRM.Models.Email;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace CRM.ViewModels.Email
{
    public class EmailMarketingVM
    {
        private readonly MyDbContext _dbContext;

        public EmailMarketingVM(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public int Id { get; set; }
        public int UserId { get; set; }
        public int OemId { get; set; }
        public int CompanyId { get; set; }
        public int GroupId { get; set; }
        public string Title { get; set; }
        public string[] Addresser { get; set; }
        public bool ShowAsEmail { get; set; }

        // 客户端发送可以不填
        // [EmailAddress]
        public string ReplyEmail { get; set; }
        // public record AddresseeObject(int? id, string name=default, string email="",bool isRead=false,bool isReply=false,[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]bool  isFailed=true);

        public record AddresseeObject(
            int? id,
            string name = default,
            string email = "",
            EmailValidationType Valid = EmailValidationType.Unknown,
            bool isRead = false,
            bool isReply = false,
            bool isFailed = true);

        public AddresseeObject[] Addressee { get; set; }
        public string EmailSubject { get; set; }
        public string EmailContent { get; set; }
        public string EmailTemplateIds { get; set; }
        public int SubmitNum { get; set; }
        public int SendingNum { get; set; }
        public int OpenNum { get; set; }
        public int ReplyNum { get; set; }
        public EmailMarketing.TypeEnum Type { get; set; }
        public EmailMarketing.StateEnum State { get; set; }
        public DateTime? TimingTransmission { get; set; }

        /// <summary>
        /// 邮件发件人名称Id
        /// </summary>
        public int? EmailSenderNameId { get; set; }

        /// <summary>
        /// 邮件发件人名称
        /// </summary>
        [MinLength(1), MaxLength(20)]
        public string EmailSenderName { get; set; }

        public string TypeOfRequest { get; set; }

        public string Server { get; set; } = string.Empty;

        private EmailPlatform EmailPlatform => Server.Equals("rushemail", StringComparison.InvariantCultureIgnoreCase)
            ? EmailPlatform.Rushmail
            : EmailPlatform.Mailjet;

        //public List<string> Images
        //{
        //    get => ImagesStr.Split(',').ToList();
        //    set => ImagesStr = string.Join(',', value);
        //}

        public async Task<EmailMarketing> NewModel(MyDbContext dbContext, Models.User user)
        {
            var addresserInfoJson = "[]";
            var freeEmailSettingJson = "{}";
            var type = EmailMarketing.TypeEnum.Server;
            switch (TypeOfRequest)
            {
                case "server":

                    break;
                case "free":
                    var res =
                        await dbContext.EmailConfig
                            .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId &&
                                        m.GroupId == user.GroupId && m.UserId == user.Id)
                            .Where(m => Addresser.Contains(m.Id.ToString())).ToListAsync();
                    var info = res.Select((r) => new
                        { r.Id, r.EmailType, r.Driver, r.Host, r.Port, r.EmailAddress, r.Secret, r.Ssl }).ToList();
                    addresserInfoJson = JsonConvert.SerializeObject(info);
                    freeEmailSettingJson = JsonConvert.SerializeObject(new FreeEmailSetting()
                    {
                        MinSendInterval = MinSendInterval,
                        MaxSendInterval = MaxSendInterval,
                        SendMethod = SendMethod,
                        SendTemplateMethod = SendTemplateMethod,
                        TrackReadStatus = TrackReadStatus,
                    });
                    type = EmailMarketing.TypeEnum.Free;
                    break;
            }

            var addresseeInfoFilter = Addressee.DistinctBy(r => r.email.ToLower())
                .Where(m => m.Valid != EmailValidationType.Invalid);
            var blackLists = await dbContext.EmailBlackLists.Where(b =>
                    b.OemId == user.OemId && b.CompanyId == user.CompanyId && b.GroupId == user.GroupId &&
                    b.UserId == user.Id)
                .Select(b => b.Email).ToArrayAsync();
            addresseeInfoFilter = addresseeInfoFilter.Where(f => !blackLists.Contains(f.email));
            var addresseeInfo = addresseeInfoFilter.Select(r => new AddresseeObj()
                { Addressee = r.email, Name = r.name, Id = r.id, IsRead = false, IsReply = false, IsFailed = true });
            var submitNum = addresseeInfo.Count();
            var settings = dbContext.Oem.Where(o => o.Id == user.OemId).Select(o => o.EmailSettings.EmailPlatform)
                .First();
            var emailPlatform = settings;
            var addresseeInfoJson = JsonConvert.SerializeObject(addresseeInfo);
            // 获取发件人名称关联
            EmailSenderName? emailSenderName = null;
            if (EmailSenderNameId is not null)
            {
                emailSenderName = dbContext.EmailSenderNames.Find(EmailSenderNameId);
            }
            else if (!string.IsNullOrWhiteSpace(EmailSenderName))
            {
                var name = EmailSenderName.Trim();
                emailSenderName = dbContext.EmailSenderNames.Where(e =>
                        e.OemId == user.OemId && e.CompanyId == user.CompanyId && e.GroupId == user.GroupId &&
                        e.UserId == user.Id && e.Name == name)
                    .FirstOrDefault();

                if (emailSenderName is null)
                {
                    emailSenderName = new EmailSenderName()
                    {
                        UserId = user.Id,
                        OemId = user.OemId,
                        CompanyId = user.CompanyId,
                        GroupId = user.GroupId,
                        Name = name,
                    };
                }
            }

            if (emailSenderName is not null)
            {
                emailSenderName.LatestUsedTime = DateTime.Now;
            }

            var resultModel = new EmailMarketing()
            {
                UserId = user.Id,
                OemId = user.OemId,
                CompanyId = user.CompanyId,
                GroupId = user.GroupId,
                Title = Title,
                State = State,
                Type = type,
                Addresser = addresserInfoJson,
                FreeEmailSetting = freeEmailSettingJson,
                ShowAsEmail = ShowAsEmail,
                ReplyEmail = ReplyEmail,
                SubmitNum = submitNum,
                Addressee = addresseeInfoJson,
                EmailContent = EmailContent,
                EmailSubject = EmailSubject,
                EmailTemplateIds = EmailTemplateIds,
                TimingTransmission = TimingTransmission ?? DateTime.Now,
                EmailPlatform = emailPlatform,
                EmailSenderName = emailSenderName,
                CreatedAt = DateTime.Now,
                UpdatedAt = DateTime.Now,
            };
            return resultModel;
        }

        public int MaxSendInterval { get; set; }

        public int MinSendInterval { get; set; }
        public SendMethod SendMethod { get; set; }
        public SendMethod SendTemplateMethod { get; set; }
        public bool TrackReadStatus { get; set; }

        public string JsonSerializer(object o)
        {
            DataContractJsonSerializer se = new DataContractJsonSerializer(o.GetType(),
                new DataContractJsonSerializerSettings()
                {
                    UseSimpleDictionaryFormat = true
                });
            //实例化一个内存流，用于存放序列化后的数据
            MemoryStream stream = new MemoryStream();
            //使用WriteObject序列化对象
            se.WriteObject(stream, o);
            //写入内存流中
            byte[] dataBytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(dataBytes, 0, (int)stream.Length);
            //通过UTF8格式转换为字符串
            return Encoding.UTF8.GetString(dataBytes);
        }

        //public SocialMarketingTask EditModel(SocialMarketingTask task)
        //{
        //    task.Name = Name;
        //    task.Content = Content;
        //    task.ImagesStr = ImagesStr;
        //    task.UpdatedAt = DateTime.Now;
        //    return task;
        //}
    }


    public class EmailMarketingListQuery
    {
        public DateTime[] CreatedAt { get; set; }
        public int? State { get; set; }
        public string Title { get; set; }
        public int Limit { get; set; }
        public int Page { get; set; }
        public int[] Ids { get; set; }
    }
}